<template>
  <div class="writeScene">
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/roleLimitManageMain' }">角色权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{isWrite ? '编辑' : '添加'}}</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <div class="title">{{isWrite ? '编辑角色' : '添加角色'}}</div>
    <!-- 中间表单 -->
    <div class="main">
      <div class="header">
        <span></span>
        <p>角色信息</p>
      </div>
      <el-form :model="param" :rules="rules" ref="ruleForm" label-width="300px">
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="param.name" placeholder="请输入角色名称" style="width:400px"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDescribe">
          <el-input
            type="textarea"
            placeholder="请输入角色描述"
            v-model="param.roleDescribe"
            maxlength="50"
            show-word-limit
            :rows="8"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限设置：" prop="crmProjectAuthorityCodes">
          <div class="wrap">
            <div class="title" @click="platformContentShow">
              <span>平台后台权限</span>
              <div class="allCheck">
                全选
                <el-checkbox v-model="platformCheckAll" @change="handlePlatformCheckAllChange"></el-checkbox>
              </div>
            </div>
            <div class="contentPlatform">
              <template v-if="authorityList && authorityList.length>0">
                <div class="item" v-for="(first,firIndex) in authorityList" :key="first.code">
                  <div class="itemHeader" @click="platformItemContentShow(firIndex)">
                    <span>{{first.codeDesc}}</span>
                    <span
                      style="color:#4868FF;margin-left:5px;"
                      v-if="first.children"
                    >{{iconShow ? '+' : '-'}}</span>
                    <el-checkbox
                      v-model="groupList"
                      :label="first.code"
                      :key="first.code"
                      @change="platformFirstChanged(firIndex)"
                    >{{''}}</el-checkbox>
                  </div>
                  <div class="itemContentPlatform">
                    <div v-for="(second,secondIndex) in first.children" :key="second.code">
                      <div class="thirdHeader">
                        <span>{{second.codeDesc}}</span>
                        <el-checkbox
                          v-model="groupList"
                          :label="second.code"
                          :key="second.code"
                          @change="platformSecondChanged(firIndex,secondIndex)"
                        >{{''}}</el-checkbox>
                      </div>
                      <div class="thirdContent">
                        <div v-for="third in second.children" :key="third.code">
                          <div>
                            <span>{{third.codeDesc}}</span>
                            <el-checkbox
                              v-model="groupList"
                              :label="third.code"
                              :key="third.code"
                              @change="thirdChanged(firIndex,secondIndex)"
                            >{{''}}</el-checkbox>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
          <div class="wrap">
            <div class="title" @click="contentShow">
              <span>项目后台权限</span>
              <div class="allCheck">
                全选
                <el-checkbox v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
              </div>
            </div>
            <div class="content">
              <template v-if="projectAuthorityList && projectAuthorityList.length>0">
                <div
                  class="item"
                  v-for="(first,firIndex) in projectAuthorityList"
                  :key="first.code"
                >
                  <div class="itemHeader" @click="itemContentShow(firIndex)">
                    <span>{{first.codeDesc}}</span>
                    <span
                      style="color:#4868FF;margin-left:5px;"
                      v-if="first.children"
                    >{{iconShow ? '+' : '-'}}</span>
                    <el-checkbox
                      v-model="proGroupList"
                      :label="first.code"
                      :key="first.code"
                      @change="firstChanged(firIndex)"
                    >{{''}}</el-checkbox>
                  </div>
                  <div class="itemContent">
                    <div v-for="second in first.children" :key="second.code">
                      <span>{{second.codeDesc}}</span>
                      <el-checkbox
                        v-model="proGroupList"
                        :label="second.code"
                        :key="second.code"
                        @change="secondChanged(firIndex)"
                      >{{''}}</el-checkbox>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
          <div v-if="isShowTip" class="errorText">请选择角色权限</div>
        </el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  updateRoleType,
  saveRoleType,
  getProjectPermissions,
  getPermissions,
  getRole
} from '../../../../api/roleLimitManage'
export default {
  data () {
    return {
      isShowTip: false,
      param: {
        roleId: '',
        name: '',
        roleDescribe: '',
        crmAuthorityCodes: [
          {
            code: '',
            codeDesc: ''
          }
        ],
        crmProjectAuthorityCodes: [
          {
            code: '',
            codeDesc: ''
          }
        ]
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      projectAuthorityList: [],
      proGroupList: [], // 选中的平台后台权限组合
      childrenList: [],
      isIndeterminate: false,
      checkAll: false,
      iconShow: false,
      authorityList: [],
      groupList: [], // 选中的项目后台权限组合
      platformCheckAll: false
    }
  },
  mounted () {
    this.getRoleInfo()
  },
  computed: {
    isWrite () {
      const userId = sessionStorage.getItem('infoId')
      return !!userId
    }
  },
  watch: {
    'param.crmAuthorityCodes': {
      handler (groups, oldGroups) {
        if (groups.toString() === oldGroups.toString()) return
        this.groupList = Array.from(groups, (obj) => obj.code)
      }
    },
    groupList (groupList) {
      const crmAuthorityCodes = []
      if (this.authorityList.length === 0) return
      groupList.forEach((o) => {
        const finder = this.authorityList.find((child) => child.code === o)
        if (finder) {
          crmAuthorityCodes.push({
            id: finder.id,
            code: finder.code,
            codeDesc: finder.codeDesc
          })
        }
        this.authorityList.forEach((e) => {
          if (e.children === null) return
          const finder = e.children.find((child) => child.code === o)
          if (finder) {
            crmAuthorityCodes.push({
              id: finder.id,
              code: finder.code,
              codeDesc: finder.codeDesc
            })
          }
          const thirdChild = e.children
          thirdChild.forEach((e) => {
            if (e.children === null) return
            const finder = e.children.find((child) => child.code === o)
            if (finder) {
              crmAuthorityCodes.push({
                id: finder.id,
                code: finder.code,
                codeDesc: finder.codeDesc
              })
            }
          })
        })
      })
      this.param.crmAuthorityCodes = crmAuthorityCodes
    },
    'param.crmProjectAuthorityCodes': {
      handler (groups, oldGroups) {
        if (groups.toString() === oldGroups.toString()) return
        this.proGroupList = Array.from(groups, (obj) => obj.code)
      }
    },
    proGroupList (proGroupList) {
      const crmProjectAuthorityCodes = []
      if (this.projectAuthorityList.length === 0) return
      proGroupList.forEach((o) => {
        const finder = this.projectAuthorityList.find(
          (child) => child.code === o
        )
        if (finder) {
          crmProjectAuthorityCodes.push({
            id: finder.id,
            code: finder.code,
            codeDesc: finder.codeDesc
          })
        }
        this.projectAuthorityList.forEach((e) => {
          if (e.children === null) return
          const finder = e.children.find((child) => child.code === o)
          if (finder) {
            crmProjectAuthorityCodes.push({
              id: finder.id,
              code: finder.code,
              codeDesc: finder.codeDesc
            })
          }
        })
      })
      this.param.crmProjectAuthorityCodes = crmProjectAuthorityCodes
    }
  },
  methods: {
    async getRoleInfo () {
      await getProjectPermissions().then((res) => {
        this.projectAuthorityList = res.data.data.children
      })
      await getPermissions().then((res) => {
        this.authorityList = res.data.data.children
      })
      const userId = sessionStorage.getItem('infoId')
      if (userId) {
        getRole(userId).then((res) => {
          if (res.data.code === 200) {
            const crmAuthority = res.data.data
            this.param.roleId = crmAuthority.id
            this.param.name = crmAuthority.name
            this.param.roleDescribe = crmAuthority.roleDescribe
            this.proGroupList = crmAuthority.authorityList
            this.groupList = crmAuthority.authorityList
            this.isPlatformCheckAll()
            this.isCheckAll()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            })
          }
        })
      }
    },
    submitForm (ruleForm) {
      this.isShowTip = (!this.groupList.length) || (!this.proGroupList.length)
      this.$refs[ruleForm].validate((valid) => {
        if (valid && !this.isShowTip) {
          if (this.isWrite) {
            // console.log(this.param)
            updateRoleType(this.param, this.param.roleId).then((res) => {
              if (res.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.message
                })
                this.$store.dispatch(
                  'roleLimitManage/updateTable',
                  this.pageIndex
                )
                this.isShowTip = false
                // this.$store.dispatch('user/getUserInfo')
                this.$router.push('/roleLimitManageMain')
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.message
                })
              }
            })
          } else {
            saveRoleType(this.param).then((res) => {
              if (res.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.message
                })
                this.$store.dispatch(
                  'roleLimitManage/updateTable',
                  this.pageIndex
                )
                this.isShowTip = false
                this.$router.push('/roleLimitManageMain')
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.message
                })
              }
            })
          }
        } else {
          this.$message({
            message: '请填写相关信息',
            type: 'error',
            duration: 500
          })
        }
      })
    },
    contentShow () {
      const element = document.getElementsByClassName('content')[0]
      if (element.style.display === 'none') {
        element.style.display = 'block'
      } else {
        element.style.display = 'none'
      }
    },
    itemContentShow (index) {
      const element = document.getElementsByClassName('itemContent')[index]
      if (element.style.display === 'none') {
        element.style.display = 'block'
        this.iconShow = true
      } else {
        element.style.display = 'none'
        this.iconShow = false
      }
    },
    handleCheckAllChange () {
      const groupOptions = []
      if (this.checkAll) {
        this.projectAuthorityList.forEach((e) => {
          groupOptions.push(e.code)
          if (e.children) {
            e.children.forEach((o) => {
              groupOptions.push(o.code)
            })
          }
        })
        this.proGroupList = groupOptions
      } else {
        this.proGroupList = []
      }
    },
    // 项目
    isCheckAll () {
      this.checkAll = this.projectAuthorityList.every((s) => {
        if (this.proGroupList.includes(s.code)) {
          return true
        }
      })
    },
    firstChanged (firIndex) {
      this.isCheckAll()
      const arr = this.projectAuthorityList[firIndex]
      const isCheck = this.proGroupList.includes(arr.code)
      if (arr.children) {
        if (isCheck) {
          arr.children.forEach((e) => {
            if (!this.proGroupList.includes(e.code)) {
              this.proGroupList.push(e.code)
            }
          })
        } else {
          arr.children.forEach((e) => {
            // this.proGroupList.splice(
            //   this.proGroupList.findIndex(item => item === e.code)
            // )
            this.proGroupList = this.proGroupList.filter((t) => t !== e.code)
          })
        }
      }
    },
    secondChanged (firIndex) {
      const arr = this.projectAuthorityList[firIndex]
      const firIndexArray = arr.children.map((item) => {
        return item.code
      })
      const isCheck = firIndexArray.some((code) => {
        return this.proGroupList.includes(code)
      })
      if (isCheck) {
        this.proGroupList.push(arr.code)
        this.isCheckAll()
      } else {
        if (this.proGroupList.includes(arr.code)) {
          this.proGroupList = this.proGroupList.filter((t) => t !== arr.code)
          this.checkAll = false
        }
      }
    },
    platformContentShow () {
      const element = document.getElementsByClassName('contentPlatform')[0]
      if (element.style.display === 'none') {
        element.style.display = 'block'
      } else {
        element.style.display = 'none'
      }
    },
    platformItemContentShow (index) {
      const element = document.getElementsByClassName('itemContentPlatform')[
        index
      ]
      if (element.style.display === 'none') {
        element.style.display = 'block'
        this.iconShow = true
      } else {
        element.style.display = 'none'
        this.iconShow = false
      }
    },
    handlePlatformCheckAllChange () {
      const groupOptions = []
      if (this.platformCheckAll) {
        this.authorityList.forEach((e) => {
          groupOptions.push(e.code)
          if (e.children) {
            e.children.forEach((o) => {
              groupOptions.push(o.code)
              if (o.children) {
                o.children.forEach((s) => {
                  groupOptions.push(s.code)
                })
              }
            })
          }
        })
        this.groupList = groupOptions
      } else {
        this.groupList = []
      }
    },
    isPlatformCheckAll () {
      this.platformCheckAll = this.authorityList.every((s) => {
        if (this.groupList.includes(s.code)) {
          return true
        }
      })
    },
    platformFirstChanged (firIndex) {
      this.isPlatformCheckAll()
      const arr = this.authorityList[firIndex]
      const isCheck = this.groupList.includes(arr.code)
      if (arr.children) {
        if (isCheck) {
          arr.children.forEach((e) => {
            if (!this.groupList.includes(e.code)) {
              this.groupList.push(e.code)
              if (e.children) {
                e.children.forEach((t) => {
                  this.groupList.push(t.code)
                })
              }
            }
          })
        } else {
          arr.children.forEach((e) => {
            // this.groupList.splice(
            //   this.groupList.findIndex(item => item === e.code)
            // )
            this.groupList = this.groupList.filter((t) => t !== e.code)
            if (e.children) {
              e.children.forEach((s) => {
                this.groupList = this.groupList.filter((t) => t !== s.code)
              })
            }
          })
        }
      }
    },
    platformSecondChanged (firIndex, secondIndex) {
      const arr = this.authorityList[firIndex].children[secondIndex] // 当前操作权限
      if (arr.children) {
        arr.children.forEach((child) => {
          if (this.groupList.includes(arr.code)) {
            // 当前权限选中，那么子权限也应自动全部勾选
            this.groupList.push(child.code)
          } else {
            // 当前权限取消，那么子权限也应自动全部取消
            this.groupList = this.groupList.filter((t) => t !== child.code)
          }
        })
      }

      const arrParent = this.authorityList[firIndex] // 一级权限
      const firIndexArray = arrParent.children.map((item) => {
        return item.code
      })
      const isFirstCheck = firIndexArray.some((code) => {
        return this.groupList.includes(code)
      })
      if (isFirstCheck) {
        this.groupList.push(arrParent.code)
        // 再判断是否全选
        this.isPlatformCheckAll()
      } else {
        if (this.groupList.includes(arrParent.code)) {
          this.groupList = this.groupList.filter((t) => t !== arrParent.code)
          this.platformCheckAll = false
        }
      }
    },
    // 当前操作权限三级
    thirdChanged (firIndex, secondIndex) {
      // isSecondCheck判断二级权限是否勾选
      const arr = this.authorityList[firIndex].children[secondIndex] // 二级权限
      const arrParent = this.authorityList[firIndex] // 一级权限
      const secIndexArray = arr.children.map((item) => {
        return item.code
      })
      const isSecondCheck = secIndexArray.some((code) => {
        return this.groupList.includes(code)
      })
      if (isSecondCheck) {
        this.groupList.push(arr.code) // 二级权限勾选

        // isFirstCheck判断一级权限是否勾选
        const firIndexArray = arrParent.children.map((item) => {
          return item.code
        })
        const isFirstCheck = firIndexArray.some((code) => {
          return this.groupList.includes(code)
        })
        if (isFirstCheck) {
          this.groupList.push(arrParent.code) // 一级权限勾选

          // platformCheckAll判断是否全选
          this.isPlatformCheckAll()
        }
      } else {
        // 二级权限不勾选
        if (this.groupList.includes(arr.code)) {
          this.groupList = this.groupList.filter((t) => t !== arr.code)
          this.groupList = this.groupList.filter((t) => t !== arrParent.code)
          this.platformCheckAll = false
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/writeBox.scss";
.writeScene {
  padding: 0 30px 30px 30px !important;
  .navButton {
    padding: 0;
    color: #4868ff;
  }
  .main {
    //height: 750px !important;
    ::v-deep .el-form {
      position: relative;
      height: calc(100% - 85px);
      .el-form-item__content {
        display: inline-block;
      }
      .el-input {
        width: 400px;
      }
      .el-textarea__inner {
        width: 560px;
      }
      .wrap {
        width: 560px;
        margin-bottom: 30px;
        .title {
          width: 560px;
          height: 60px;
          font-size: 14px;
          background: rgba(87, 131, 255, 0.05);
          padding: 12px 16px;
          border-bottom: 1px solid #e6e6e6;
          span {
            font-weight: 600;
            color: #333333;
          }
          .allCheck {
            float: right;
            .el-checkbox {
              margin-left: 10px;
            }
          }
        }
        .contentPlatform {
          .itemHeader {
            padding: 8px 6px 8px 16px;
            border-bottom: 1px solid #e6e6e6;
            height: 60px;
            color: #000000;
            .el-checkbox {
              float: right;
            }
          }
          .itemContentPlatform {
            padding: 0px 6px 0px 16px;
            border-bottom: 1px solid #e6e6e6;
            color: #666666;
            .el-checkbox {
              float: right;
            }
            .thirdContent {
              padding-left: 14px;
              font-weight: 100;
            }
          }
        }
        .content {
          .itemHeader {
            padding: 8px 6px 8px 16px;
            border-bottom: 1px solid #e6e6e6;
            height: 60px;
            color: #000000;
            .el-checkbox {
              float: right;
            }
          }
          .itemContent {
            padding: 0px 6px 0px 16px;
            border-bottom: 1px solid #e6e6e6;
            color: #666666;
            .el-checkbox {
              float: right;
            }
          }
        }
      }
      .errorText {
        color: #f56c6c;
        font-size: 12px;
        line-height: 1;
      }
      .el-button {
        //position: absolute;
        //bottom: 30px;
        margin-left: 300px;
        margin-bottom: 30px;
        width: 172px;
        height: 48px;
        background: rgba(72, 104, 255, 1);
        border-radius: 24px;
      }
    }
  }
  ::v-deep .el-form {
    .el-form-item.is-required:not(.is-no-asterisk)
      .el-form-item__label-wrap
      > .el-form-item__label:before,
    .el-form-item.is-required:not(.is-no-asterisk)
      > .el-form-item__label:before {
      content: "*";
      color: #4868ff;
      margin-right: 4px;
    }
    .el-form-item__label{
      width: 300px !important;
    }
    .el-form-item__error {
      color: #f56c6c;
      font-size: 12px;
      line-height: 1;
      padding-top: 4px;
      position: absolute;
    }
    // .content {
    //   .el-checkbox {
    //     display: flex;
    //     justify-content: space-between;
    //     align-items: center;
    //     flex-direction: row-reverse;
    //     height: 60px;
    //   }
    // }
  }
}
</style>
